package cn.itcast.web.controller.system;

import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;



@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {
    @Autowired
    private DeptService deptService;

    /**
     * 分页查找所有的部门数据
     * @param pageNum 当前页 默认为1
     * @param pageSize 每页数据条数 默认为5
     * @return
     */
    @RequestMapping("list")
    public String findAll( @RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "5") Integer pageSize){

        PageInfo<Dept> pageInfo = deptService.findByPage(getLoginCompanyId(), pageNum, pageSize);
        System.out.println(pageInfo);
        request.setAttribute("pageInfo",pageInfo);
        return "/system/dept/dept-list";
    }

    /**
     * 根据企业查询所有部门数据，跳转添加页面
     * @return 跳转页面地址
     */
    @RequestMapping("toAdd")
    public String toAdd(){
        List<Dept> all = deptService.findAll(getLoginCompanyId());
        request.setAttribute("deptList",all);
        return "/system/dept/dept-add(1)";
    }

    /**
     * 修改或保存，当id的值为空时执行save方法否则执行update方法
     * @param dept 部门对象
     * @return
     */
    @RequestMapping("edit")
    public String edit(Dept dept){
        dept.setCompanyId(getLoginCompanyId());
        dept.setCompanyName(getLoginCompanyName());
        if (StringUtils.isEmpty(dept.getId())){
            deptService.save(dept);
        }else {
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }

    /**
     * 查询上级部门，跳转到修改页面
     * @param id 部门id
     * @return 跳转地址
     */
    @RequestMapping("toUpdate")
    public String toUpdate(String id){
        List<Dept> parent = deptService.findParent(id, getLoginCompanyId());
        Dept dept = deptService.findById(id);
        request.setAttribute("dept",dept);
        request.setAttribute("deptList",parent);
        return "/system/dept/dept-update";
    }

    /**
     * 根据id删除指定部门
     * @param id 部门id
     * @return 返回影响行数
     */
    @RequestMapping("delete")
    public String delete(String id){
        Integer delete = deptService.delete(id);
        return "redirect:/system/dept/list.do";
    }

}
